/**
 * 
 */
package cc.rico.shiro.realm;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.SimpleByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cc.rico.shiro.utils.CredentialsUtil;

/**
 * 系统验证Realm
 * @author rico 2016年6月22日
 *
 */
public class CustomAuthorizeRealm extends AuthorizingRealm {
	private static final Logger logger = LoggerFactory.getLogger(CustomAuthorizeRealm.class);

	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		logger.info("##doGetAuthorizationInfo.principal = {}", principals.getPrimaryPrincipal());
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		
		Set<String> roles = new HashSet<String>();
		roles.add("admin");
		roles.add("system");
		authorizationInfo.addRoles(roles);
		
		List<String> permissions = new ArrayList<String>();
		permissions.add("/home/add");
		permissions.add("/home/delete");
		permissions.add("/home/update");
		authorizationInfo.addStringPermissions(permissions);
		
		return authorizationInfo;
	}

	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String authUsername = "rico";
		String authCredentials = "admin";
		String salt = "//Nm3uvL79g8JR2VYyZ0e9yg==";
		String encodeCredentials = CredentialsUtil.encodeToHex(Md5Hash.ALGORITHM_NAME, 1, salt, authCredentials);
		logger.info("##username={}, encodeCredentials={}", authUsername, encodeCredentials);
		
		ByteSource credentialsSalt = new SimpleByteSource(salt);
		return new SimpleAuthenticationInfo(authUsername, encodeCredentials, credentialsSalt, authUsername);
	}
	
//	private String calculateCredentials(Object credentials) {
//		String salt = "//Nm3uvL79g8JR2VYyZ0e9yg==";
//		
//		HashRequest hashRequest = new HashRequest.Builder()
//			.setAlgorithmName(Md5Hash.ALGORITHM_NAME)
//			.setIterations(1)
//			.setSalt(salt)
//			.setSource(credentials)
//			.build();
//	 
//		HashService hashService = new DefaultHashService();
//		Hash hash = hashService.computeHash(hashRequest);
//		
//		return hash.toHex();
//	}
	
}
